# coding=utf-8
import os
import re
import sys
import traceback

import akshare as ak
import pandas
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv


def run(d=1):
    if d:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv("shanghai_index.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index.csv')
    today_date = eval(str(list(df_sorted['日期'])[0]).replace('-', ''))
    return today_date


def get_3down_len(today_date, sn, N):
    """
    获取最近N次下跌，连续下跌天数计数
    """
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None, None, None, None
    df = pandas.read_csv(sc)
    if str(df['trade_date'][0]) != str(today_date):
        analysis_stock(sn)
        df = pandas.read_csv(sc)
    result_arr = []
    d_arr = []
    today_d = None
    down_N = 0
    for row in df.index:
        d = DayInfo(sn, df.loc[row])
        if d.pct_chg > 0 and row == 0:
            return None, None, None, None
        if row < N - 1 and d.pct_chg <= 0:
            down_N += 1
        if today_d is None:
            today_d = d
        if len(d_arr) == N:
            break
        result_arr.append(d.close)
        if d.pct_chg <= 0:
            d_arr.append(d)
        else:
            d_arr = []
    res = re.findall('stocks/(.*).csv', sc)
    link_code_arr = res[0].split('.')
    link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
    hyperlink = f'"https://xueqiu.com/S/{link_code}"'
    date_arr_hyp = f'=HYPERLINK({hyperlink})'
    # 今日收盘价排前1/3
    max_len = len(result_arr) - N
    if max_len < 10:
        return None, None, None, None
    q_index = max_len // 3
    result_arr.sort(reverse=True)
    if today_d.close in result_arr[:q_index]:
        return today_d, len(result_arr) - N, date_arr_hyp, down_N
    return None, None, None, None


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


if __name__ == '__main__':
    # 获取离最近一次N连跌的距离排序
    N = 4
    try:
        if len(sys.argv) == 2:
            N = int(sys.argv[1])
        else:
            N = 4
    except Exception as e:
        logger.error(e)
        N = 4
    while N > 2:
        N -= 1
        D = True
        today_date = run(D)
        full_path_tk = f'{today_date}_down3_N{N}.csv'
        f_tk = open(full_path_tk, 'w', encoding='utf-8')
        f_tk.write(f'行业,名称,down3,当前价格,涨跌幅,DN,连接')
        df = pd.read_csv('cal_ops/all.csv')
        full_path_txt = f'{today_date}_get_down3_N{N}.txt'
        if os.path.exists(full_path_txt):
            os.remove(full_path_txt)
        logger.add(full_path_txt, format='{message}')
        n_arr = []
        ts_code_arr = []
        result_dict = {}
        for row in df.index:
            sn = StockNumber(df.loc[row])
            logger.info(f'N={N} {sn.name}')
            if 'ST' in sn.name:
                continue
            # if sn.name not in [
            #     '青岛港',
            #     '长安汽车',
            # ]:
            #     continue
            try:
                """
                    elf.name = sn.name
                    self.ts_code = sn.ts_code
                    self.industry = sn.industry
                    self.trade_date = df_row_data['trade_date']
                    self.open = df_row_data['open']
                    self.high = df_row_data['high']
                    self.low = df_row_data['low']
                    self.close = float(df_row_data['close'])
                    self.pre_close = df_row_data['pre_close']
                    self.change = df_row_data['change']
                    self.pct_chg = float(df_row_data['pct_chg'])
                    self.vol = df_row_data['vol']
                    self.amount = df_row_data['amount']
                """
                today_d, max_len, date_arr_hyp, down_N = get_3down_len(today_date, sn, N)
                if today_d is None and max_len is None and max_len is None:
                    continue
                rhs_pct = round(today_d.pct_chg, 2)
                w_msg = f'\n{sn.industry},{sn.name},{max_len},{today_d.close},{rhs_pct},{down_N},{date_arr_hyp}'
                f_tk.write(w_msg)
                f_tk.flush()
            except Exception as e:
                print(e, traceback.format_exc())

        if os.path.exists(full_path_txt):
            os.remove(full_path_txt)

        f_tk.close()
        sort_csv(full_path_tk, ['down3', '行业', 'DN'], [False, True, False])
